import React from "react";
import axios from "axios";
import { useState, useEffect } from "react";
import PubSub from "pubsub-js";
import {Link, useNavigate} from 'react-router-dom'

export default function HeroList() {
  //声明状态
  let [heros, setHeros] = useState([]);
  // input 的状态声明,必须为空不然就会执行挂载
  let [keyword, setKeyword] = useState();
  // 是否第一次
  let [isFirst , setIsFirst] = useState(true)
  // 加载
  let [loading,setLoading] = useState(true)
  let navigater = useNavigate()
  let getHeros = async () => {
    setIsFirst(false)
    setLoading(false)
    setHeros([])
    let result = await axios.get("http://api.xiaohigh.com/heros", {
      params: {
        name_like: keyword,
      },
    });
    setHeros(result.data);
    setLoading(true)
  };

  //组件挂载完毕
  useEffect(() => {
    if(keyword === undefined) return
    getHeros();
  }, [keyword]);

  useEffect(() => {
    // 订阅
    PubSub.subscribe("keyword", async (name, data) => {
      setKeyword(data);
    });
  }, []);
  return (
    <div className="hero-list">
      {isFirst && <h2 style={{textAlign:'center', marginTop:50 }}>欢迎来到英雄联盟</h2>}
      {!loading && <h2>加载中</h2>}
      {!isFirst && loading && heros.length === 0 && <h2>网络异常</h2>}
      {heros.map((item) => {
        return (
          <div key={item.id} className="hero-item">
            <img onClick={()=>{
              navigater('/heros',{
                // 替换
                // replace:true,
                state:{
                  id:item.id
                }
              })
            }} src={"https://cdn.xiaohigh.com" + item.image} alt="" />
            <p>{item.name}</p>
          </div>
        );
      })}
    </div>
  );
}
